/* 7. 添加读者 */


const CHECK = require("../myUtil/formatCheck");
const db = require("../../coSqlite3");
const HTM = require("../myUtil/lib").html;

exports.addUser = function* (req, res) {
    console.log("----------------------7. 添加读者\n");
    let rID = req.body.rID;
    let rName = req.body.rName;
    let rSex = req.body.rSex;
    let rDept = req.body.rDept;
    let rGrade = req.body.rGrade;


    let htm = HTM.divBegin + 2 + HTM.divEnd + '提交的参数有误';
    if (rID == '') {
        return HTM.begin + htm + '证号不能为空' + HTM.end;
    } else if (rID.length > 8) {
        return HTM.begin + htm + '证号长度不能超过8' + HTM.end;
    }

    if (rName.length > 10) {
        return HTM.begin + htm + '姓名长度不能超过10' + HTM.end;
    }

    // if ('女' != rSex && '男' != rSex) {
    if (rSex != '' && !(rSex == '男' || rSex == '女')) {
        return HTM.begin + htm + '请填写男或女' + HTM.end;
    }

    if (rDept.length > 10) {
        return HTM.begin + htm + '系名长度不能超过30' + HTM.end;
    }

    if ("" != rGrade && CHECK.isNotPositiveInt(rGrade)) {
      return HTM.begin + htm + "年级请填写正整数" + HTM.end;
    }

    let args = [rID, rName, rSex != ''? rSex : '男', rDept, rGrade];

    let rows;
    htm = HTM.divBegin + 1 + HTM.divEnd;
    try {
        let exist = yield db.execSQL("SELECT count(rid) as count FROM reader WHERE rid = ?", [rID]);
        if (exist[0].count > 0) {
            return HTM.begin + htm + '读者已经存在' + HTM.end;
        }
        // console.log("1111")
        rows = yield db.execSQL("insert into reader values(?,?,?,?,?)", args);
    } catch (err) {
        htm = HTM.divBegin + 3 + HTM.divEnd + '数据库执行失败: ';
        return HTM.begin + htm + err + HTM.end;
    }

    htm = HTM.divBegin + 0 + HTM.divEnd;

    return HTM.begin + htm + '成功' + HTM.end;
}